package com.penton.util;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager;

public class PlatformService {

	Context ctx;
	private String tag = "PlatformService";

	public PlatformService(Context ctx) {
		this.ctx = ctx;
	}

	/**
	 * 判断 sdcard 是否存在
	 * 
	 * @return
	 */
	public boolean isSdCardExists() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
			return true;
		else
			return false;
	}

	/**
	 * 获取 sdcard 路径
	 */
	public String getSdcardPath() {
		if (isSdCardExists())
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		else
			return null;
	}

	/**
	 * sdcard 总大小 (单位bit)
	 */
	public long getAllSize() {
		if (!isSdCardExists()) {
			return 0;
		}
		// 取得 sdcard 文件路径
		File path = Environment.getExternalStorageDirectory();
		StatFs stat = new StatFs(path.getPath());
		/* 获取 block 的 SIZE */
		long blockSize = stat.getBlockSize();
		/* 块数量 */
		long availableBlocks = stat.getBlockCount();
		/* 返回 bit 大小值 */
		return availableBlocks * blockSize;
	}

	/**
	 * 取得 空闲 sdcard 空间大小 (单位bit)
	 */
	public long getAvailaleSize() {
		if (!isSdCardExists()) {
			return 0;
		}
		// 取得 sdcard 文件路径
		File path = Environment.getExternalStorageDirectory();
		StatFs stat = new StatFs(path.getPath());
		/* 获取 block 的 SIZE */
		long blockSize = stat.getBlockSize();
		/* 空闲的 block 的 数量 */
		long availableBlocks = stat.getAvailableBlocks();
		/* 返回 bit 大小值 */
		return availableBlocks * blockSize; // x/1024 Kb单位
	}

	/**
	 * 安装 apk
	 * 
	 * @param apkPath
	 *            在 /sdcard/下的路径
	 */
	public void installAPK(String apkPath) {
		String fileName = Environment.getExternalStorageDirectory()
				+ File.separator + apkPath;
		Log.i(tag, tag + " installAPK ------------:" + fileName);
		File file = new File(fileName);
		installAPK(file);
	}

	/**
	 * 安装 apk
	 */
	public void installAPK(File apkFile) {
		Log.i(tag,
				tag + " installAPK ---- getAbsolutePath:"
						+ apkFile.getAbsolutePath());
		Uri uri = Uri.fromFile(apkFile);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Log.i(tag, "FLAG_ACTIVITY_NEW_TASK:" + Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		ctx.startActivity(intent);
	}

	/**
	 * 获取网络连接的信息
	 */
	public String getNetworkInfo() {
		StringBuffer sInfo = new StringBuffer();
		ConnectivityManager cm = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm != null) {
			NetworkInfo activeNetInfo = cm.getActiveNetworkInfo();
			NetworkInfo mobNetInfo = cm
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			NetworkInfo wifiInfo = cm
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

			sInfo.append(getNetworkInfo(activeNetInfo));
			sInfo.append("\n");

			sInfo.append(getNetworkInfo(mobNetInfo));
			sInfo.append("\n");

			sInfo.append(getNetworkInfo(wifiInfo));

		}
		return sInfo.toString();
	}

	public String getNetworkInfo(NetworkInfo info) {
		StringBuffer sInfo = new StringBuffer();
		if (info != null) {
			Log.d(tag, "");
			sInfo.append("\nDetailedState:" + info.getDetailedState());
			sInfo.append("\nState:" + info.getState());
			sInfo.append("\nType:" + info.getType());
			sInfo.append("\nTypeName:" + info.getTypeName());
			sInfo.append("\nExtraInfo:" + info.getExtraInfo());

			sInfo.append("\nReason:" + info.getReason());
			sInfo.append("\nSubtype:" + info.getSubtype());
			sInfo.append("\nSubtypeName:" + info.getSubtypeName());
			sInfo.append("\nExtraInfo:" + info.getExtraInfo());
			sInfo.append("\n");
		}

		return sInfo.toString();
	}

	/**
	 * 获取已安装的软件信息
	 * 
	 * @return
	 */
	public List<HashMap<String, Object>> getInstalledApps() {
		List<ApplicationInfo> pkgs = ctx.getPackageManager()
				.getInstalledApplications(0);

		HashMap<String, Object> map;
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

		Iterator<ApplicationInfo> i = pkgs.iterator();
		while (i.hasNext()) {
			ApplicationInfo app = i.next();
			String pkgName = app.packageName;
			String label = "";
			try {
				label = ctx.getPackageManager().getApplicationLabel(app)
						.toString();
			} catch (Exception e) {
				Log.e(tag, "setLabel is error. " + e.getMessage());
			}
			map = new HashMap<String, Object>();
			map.put("name", label);
			map.put("desc", pkgName);
			list.add(map);
		}
		return list;
	}

	/**
	 * 手机信息
	 */
	public String getPhoneInfo() {
		TelephonyManager tm = (TelephonyManager) ctx
				.getSystemService(Context.TELEPHONY_SERVICE);
		String line1Num = tm.getLine1Number();

		StringBuilder s = new StringBuilder();
		// 参考网址: http://mobile.51cto.com/android-266639.htm
		s.append("\nLine1Num:" + line1Num);// 手机号码
		s.append("\nSubscriberId:" + tm.getSubscriberId());
		s.append("\nDeviceId(IMEI):" + tm.getDeviceId());

		s.append("\nModel:" + Build.MODEL); // 手机型号
		s.append("\nVERSION.SDK:" + Build.VERSION.SDK);// SDK版本号
		s.append("\nVERSION.RELEASE:" + Build.VERSION.RELEASE);// Firmware/OS
		// 版本号
		s.append("\nCPU_ABI:" + Build.CPU_ABI);
		//s.append("\nCPU_ABI2:" + Build.CPU_ABI2);
		//s.append("\nHARDWARE:" + Build.HARDWARE);

		return s.toString();
	}

	/**
	 * Wifi MacAddress
	 */
	public String getMacAddress() {
		String result = "";
		WifiManager wifiManager = (WifiManager) ctx
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		result = wifiInfo.getMacAddress();
		Log.i(tag, "macAdd:" + result);
		return result;
	}

	/**
	 * 获取手机屏幕 宽度,高度
	 * 
	 * @return [width,height]
	 */
	public int[] getWeithAndHeight() {
		// 在service中也能得到高和宽
		WindowManager wm = (WindowManager) ctx
				.getSystemService(Context.WINDOW_SERVICE);
		int w = wm.getDefaultDisplay().getWidth();
		int h = wm.getDefaultDisplay().getHeight();

		// // 这种方式在service中无法使用，
		// DisplayMetrics dm = new DisplayMetrics();
		// getWindowManager().getDefaultDisplay().getMetrics(dm);
		// String width = dm.widthPixels; // 宽
		// String height = dm.heightPixels; // 高

		return new int[] { w, h };
	}

	/**
	 * 判断某个服务是否正在运行
	 * 
	 * @param serviceName
	 * @return
	 */
	public boolean isServiceRunning(String serviceName) {
		ActivityManager manager = (ActivityManager) ctx
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo svc : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (svc.service.getClassName().equals(serviceName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Wifi IpAddress
	 */
	public String getLocalIpAddress() {

		WifiManager wifiManager = (WifiManager) ctx
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		// Note that the getIpAddress returns an integer value. To convert to
		// readable format we can use the following code:

		return String.format("%d.%d.%d.%d", (ipAddress & 0xff),
				(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
				(ipAddress >> 24 & 0xff));
	}

	public String getLocalIpAddress2() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e(tag, ex.toString());
		}
		return null;
	}

}